import sys
import os
import inspect

project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
sys.path.append(project_root)
import witin_nn

# 用于存储帮助信息的目录路径
output_dir = os.path.join(project_root, "witin_nn_help")

def write_help_to_file(module, file_path):
    """获取模块的帮助信息并写入文件"""
    try:
        help_text = inspect.getdoc(module)
        with open(file_path, "w", encoding="utf-8") as file:
            if help_text:
                file.write(f"Help for {module}:\n")
                file.write(help_text)
                file.write("\n\n")
            else:
                file.write(f"No docstring found for {module}.\n\n")
    except Exception as e:
        with open(file_path, "w", encoding="utf-8") as file:
            file.write(f"Failed to get help for {module}: {e}\n\n")

def explore_module(module, visited, base_dir):
    """递归遍历模块及其属性"""
    if module in visited:
        return
    visited.add(module)

    # 只处理以 witin_nn 开头的模块
    if not module.__name__.startswith('witin_nn'):
        return

    # 创建模块对应的文件路径
    module_name = module.__name__.replace('.', os.sep)
    file_path = os.path.join(base_dir, f"{module_name}.txt")
    os.makedirs(os.path.dirname(file_path), exist_ok=True)

    # 写入当前模块的 help 信息
    write_help_to_file(module, file_path)

    # 获取模块的所有属性
    attributes = dir(module)
    for attr_name in attributes:
        try:
            attr = getattr(module, attr_name)
            # 如果属性是一个模块，递归处理
            if inspect.ismodule(attr):
                explore_module(attr, visited, base_dir)
            # 如果属性是一个类或函数，也记录帮助信息
            elif inspect.isclass(attr) or inspect.isfunction(attr):
                attr_file_path = os.path.join(base_dir, f"{module_name}_{attr_name}.txt")
                write_help_to_file(attr, attr_file_path)
        except Exception as e:
            error_file_path = os.path.join(base_dir, f"{module_name}_errors.txt")
            with open(error_file_path, "a", encoding="utf-8") as file:
                file.write(f"Failed to access {attr_name}: {e}\n\n")

def main():
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    visited = set()
    explore_module(witin_nn, visited, output_dir)
    print(f"Help documentation written to {output_dir}")

if __name__ == "__main__":
    main()